package com.qyhl.school.school.vlog.upload;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolThemeBean;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_VLOG_UPLOAD)
public class SchoolVlogUploadActivity extends BaseActivity implements SchoolVlogUploadContract.SchoolVlogUploadView {
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.summary)
    EditText summary;
    @BindView(R2.id.video_cover)
    ImageView videoCover;
    @BindView(R2.id.vlog_tags)
    TagFlowLayout vlogTags;

    private String coverUrl;

    private String videoUrl;


    private String upSummary;

    private SchoolVlogUploadPresenter mPresenter;

    private List<Integer> tagIndex;
    private Iterator<Integer> iterator;

    private List<SchoolThemeBean> tagList;

    private int tagId;

    private boolean isUploading = false;


    /**
     * 上传token
     */
    private UpTokenBean mUpToken;

    public final static String IntentKey_VideoUrl = "IntentKey_VideoUrl";
    public final static String IntentKey_VideoCover = "IntentKey_VideoCover";

    @Override
    protected int getContentView() {
        return R.layout.activity_school_vlog_upload;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.school_vlog_publish, menu);
        return true;
    }


    @Override
    protected void init() {
        mPresenter = new SchoolVlogUploadPresenter(this);

        setSupportActionBar(toolbar);
        toolbar.inflateMenu(R.menu.school_vlog_publish);

        coverUrl = getIntent().getStringExtra("cover");
        videoUrl = getIntent().getStringExtra("video");
        tagId = getIntent().getIntExtra("tagId", 0);

        Glide.with(this)
                .load(coverUrl)
                .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                .into(videoCover);

        mPresenter.getToken(false);
        mPresenter.getTagList();
    }

    @Override
    protected void setListener() {
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.publish) {
                    if (NetUtil.isNetworkAvalible(SchoolVlogUploadActivity.this)) {
                        if (!isUploading) {
                            checkData();
                        } else {
                            showToast("正在发布中...");
                        }

                    } else {
                        showToast("网络异常，请检查您的网络！");
                    }
                }
                return false;
            }
        });
    }

    private void checkData() {
        showLoading("发布中...");
        isUploading = true;
        upSummary = summary.getText().toString();
        if (StringUtils.isEmpty(upSummary)) {
            showToast("请填写视频描述！");
            dismissLoading();
            isUploading = false;
            return;
        }

        //判断内容类型
        tagIndex = new ArrayList<>();
        iterator = vlogTags.getSelectedList().iterator();
        while (iterator.hasNext()) {
            tagIndex.add(iterator.next());
        }

        if (tagIndex.size() > 0) {
            tagId = tagList.get(tagIndex.get(0)).getId();
        } else {
            showToast("请选择参与话题！");
            dismissLoading();
            isUploading = false;
            return;
        }

        if (StringUtils.isNotEmpty(coverUrl) && StringUtils.isNotEmpty(videoUrl)) {
            if (mUpToken == null) {
                dismissLoading();
                isUploading = false;
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            UploadBean videoBean = new UploadBean();
            videoBean.setType(3);
            videoBean.setPath(videoUrl);
            videoBean.setPostion(0);
            uploadBeans.add(videoBean);

            UploadBean videoCoverBean = new UploadBean();
            videoCoverBean.setType(4);
            videoCoverBean.setPath(coverUrl);
            videoCoverBean.setPostion(0);
            uploadBeans.add(videoCoverBean);

            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getToken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    dismissLoading();
                    isUploading = false;
                    showToast("上传出错");
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    if (files != null && files.size() > 0) {
                        String upCover = "";
                        String upUrl = "";
                        for (int i = 0; i < files.size(); i++) {
                            UploadBean uploadBean = files.get(i);
                            String path = uploadBean.getUrl();
                            if (uploadBean.getType() == 3) {
                                upUrl = path;
                            } else if (uploadBean.getType() == 4) {
                                upCover = path;
                            }
                        }
                        String userName = CommonUtils.getInstance().getUserName();
                        mPresenter.upLoadData(upSummary, upUrl, upCover, userName, tagId);
                    } else {
                        dismissLoading();
                        isUploading = false;
                        showToast("上传出错");
                    }

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            showToast("视频地址或封面不能为空！");
            isUploading = false;
            dismissLoading();
        }

    }


    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            dismissLoading();
            showToast("上传失败！");
        }
    }

    @Override
    public void upLoadSuccess(String msg) {
        dismissLoading();
        showToast(msg);

        finish();
    }

    @Override
    public void upLoadError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    public void setTagList(List<SchoolThemeBean> beanList) {
        tagList = beanList;
        if (tagList != null) {
            //话题选择
            vlogTags.setMaxSelectCount(1);//最多选一个标签

            vlogTags.setAdapter(new TagAdapter<SchoolThemeBean>(tagList) {
                @SuppressLint("SetTextI18n")
                @Override
                public View getView(FlowLayout parent, int position, SchoolThemeBean tag) {
                    TextView tv = (TextView) LayoutInflater.from(SchoolVlogUploadActivity.this).inflate(R.layout.item_school_vlog_tag,
                            vlogTags, false);
                    tv.setText("#" + tag.getName() + "#");
                    return tv;
                }
            });

            if (tagId != 0) {
                for (int i = 0; i < beanList.size(); i++) {
                    if (tagId == beanList.get(i).getId()) {
                        vlogTags.getAdapter().setSelectedList(i);
                    }
                }
            }
        }


    }


    @OnClick(R2.id.video_layout)
    public void onClick() {
        Bundle bundle = new Bundle();
        bundle.putString(IntentKey_VideoUrl, videoUrl);
        bundle.putString(IntentKey_VideoCover, coverUrl);
        RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
    }
}
